package com.guodu.gdpp;

import java.text.SimpleDateFormat;
import com.guodu.comm.gdpp.message.GDPPDeliverMessage;
import com.guodu.comm.gdpp.message.GDPPMessage;
import com.guodu.comm.gdpp.message.GDPPSubmitRepMessage;
import com.guodu.gdpp.msg.MTMessage;
import com.guodu.smproxy.GDPPSubmitLongMsg;
import com.guodu.smproxy.GDPPSubmitNormalMsg;
import com.guodu.smproxy.SMProxy;
import com.guodu.util.Args;
import com.guodu.util.Util;

/**
 * 收发短信代理类
 *
 */
public class MySMProxy extends SMProxy {
	private String sign;

	public MySMProxy(Args args) {
		super(args);  //调用父类SMProxy的构造方法，一定要有！
		sign = args.get("sign", ""); //解析配置文件中签名
	}

	/**
	 * 发送普通消息
	 * @param msg 要发送的消息
	 *
	 */
	public void submitNormalMsg(MTMessage msg){
		String[] DestMobileArray = new String[1];
		DestMobileArray[0] = msg.getPhone();
		String service_ID = "";
		String Msgcont;
		int tp_PID = 0, tp_UDHI = 0, registered_Delivery = 1, pk_Total = 1, pk_Number = 1;

		String Content = msg.getContent();
		int msg_fmt = 15; //想测二进制消息，修改msg_fmt=4
		if (msg_fmt == 4) {
			String MsgField[] = Content.split(",");
			msg_fmt = Integer.parseInt(MsgField[0]);
			Msgcont = MsgField[1];
			tp_PID = Integer.parseInt(MsgField[2]);
			tp_UDHI = Integer.parseInt(MsgField[3]);
			service_ID = MsgField[4];
			registered_Delivery = Integer.parseInt(MsgField[5]);
			pk_Total = Integer.parseInt(MsgField[6]);
			pk_Number = Integer.parseInt(MsgField[7]);
		}else{
			Msgcont = Content;
		}

		try{

			GDPPSubmitRepMessage submitRepMsg = new GDPPSubmitNormalMsg().submitMessage(
			pk_Total, // pk_total
			pk_Number, // pk_number
			registered_Delivery, // registered_Delivery  是否需要状态报告回复：0表示需要回复状态报告，1表示不需要回复状态报告
			1, // msg_Level
			service_ID, // service_ID
			0, // fee_UserType
			"", // fee_Terminal_ID
			tp_PID, // tp_Pid;
			tp_UDHI, // tp_Udhi
			msg_fmt, // msg_fmt  消息内容的格式：15-为普通GBK消息；0-为ASCII消息；8-为USC编码消息；4-二进制消息；
			"", // msg_Src
			"", // fee_Type
			"", // fee_Code
			null, // valid_Time
			null, // at_Time
			msg.getAppend(), // src_Terminal_Id 扩展子号码
			DestMobileArray, // dest_Terminal_Id 目的手机号
			Msgcont, // msg_Content, 发送内容
			"",
			this,
			sign);

			if(submitRepMsg != null)
			{
				msg.setMsgid(Util.byteArrayToHexString(submitRepMsg.getMsgId()));
				msg.setStat(submitRepMsg.getResult());
			}else {
				msg.setMsgid("");
				msg.setStat(54); //超时未接收到响应消息
            }

			}catch(Exception e){
				   e.printStackTrace();
			}
	}

	/**
	 * 发送长消息
	 * @param msg 要发送的长消息
	 *
	 */
	public void submitLongMsg(MTMessage msg){
		GDPPSubmitLongMsg submitLong = new GDPPSubmitLongMsg();

		String[] DestMobileArray = new String[1];
		DestMobileArray[0] = msg.getPhone();
		String service_ID = "";
		String Msgcont;
		int tp_PID = 0, tp_UDHI = 0, registered_Delivery = 1, pk_Total = 1, pk_Number = 1;

		String Content = msg.getContent();
		int msg_fmt = 15; //想测二进制消息，修改msg_fmt=4
		if (msg_fmt == 4) {
			String MsgField[] = Content.split(",");
			msg_fmt = Integer.parseInt(MsgField[0]);
			Msgcont = MsgField[1];
			tp_PID = Integer.parseInt(MsgField[2]);
			tp_UDHI = Integer.parseInt(MsgField[3]);
			service_ID = MsgField[4];
			registered_Delivery = Integer.parseInt(MsgField[5]);
			pk_Total = Integer.parseInt(MsgField[6]);
			pk_Number = Integer.parseInt(MsgField[7]);
		} else{
			Msgcont = Content;
		}

	try{

	GDPPSubmitRepMessage submitRepMsg = submitLong.submitLongMsg(
			pk_Total, // pk_total
			pk_Number, // pk_number
			registered_Delivery, // registered_Delivery是否需要状态报告回复：0表示需要回复状态报告，1表示不需要回复状态报告
			1, // msg_Level
			service_ID, // service_ID
			0, // fee_UserType
			"", // fee_Terminal_ID
			tp_PID, // tp_Pid;
			tp_UDHI, // tp_Udhi
			msg_fmt, // msg_fmt 消息内容的格式：15-为普通GBK消息；0-为ASCII消息；8-为USC编码消息；4-二进制消息；
			 "", // msg_Src
			 "", // fee_Type
			 "", // fee_Code
			 null, // valid_Time
			 null, // at_Time
			 msg.getAppend(), // src_Terminal_Id 扩展子号码
			 DestMobileArray, // dest_Terminal_Id 目的手机号
			 Msgcont, // msg_Content, 发送内容
			 "",
			this,
			sign);

			if(submitRepMsg != null)
			{
				msg.setMsgid(Util.byteArrayToHexString(submitRepMsg.getMsgId()));
				msg.setStat(submitRepMsg.getResult());
			}else {
				msg.setMsgid("");
				msg.setStat(54); //超时未接收到响应消息
		    }

			}catch(Exception e){
				e.printStackTrace();
			}
		}

	/**
	 * 对ISMG主动下发的消息的处理,处理上行信息
	 * @param msg
	 *            收到的消息
	 * @return 返回的相应消息。
	 */
	public GDPPMessage onDeliver(GDPPDeliverMessage msg) {
		/*-- 在此处添加对消息的处理—
		 主要包括：根据Registered_Delivery字段判断此消息是普通上行消息还是回复报告。
		0．普通上行消息。
		1．回复报告。
		 */
		String srcmobile = null;
		String content = null;
		int content_type = 0;
		int ecode = -1;


		try {
		if (msg.getRegisteredDeliver() == 0) { // 消息类型,0-正常消息,1-状态报告
			 srcmobile = msg.getSrcterminalId();

			 switch (msg.getMsgFmt()) {
				case 0: // ASCII消息
					content = new String(msg.getMsgContent(), "ISO8859_1");
					break;
				case 8: // UCS编码消息
				case 15: // GBK编码消息
					String CharSetName = "UnicodeBigUnmarked";

					if (msg.getMsgFmt() == 8)
						CharSetName = "UnicodeBigUnmarked";
					if (msg.getMsgFmt() == 15)
						CharSetName = "GBK";

					if ((msg.getMsgContent().length > 3)
							&& // 是否为分段发送的多条消息
							(msg.getMsgContent()[0] == 0x05)
							&& (msg.getMsgContent()[1] == 0x00)
							&& (msg.getMsgContent()[2] == 0x03)) {

						int i = msg.getMsgContent().length - 6;
						int m = msg.getMsgContent()[4];
						int n = msg.getMsgContent()[5];
						byte b[] = new byte[i];
						System.arraycopy(msg.getMsgContent(), 6, b, 0, i);

						content = new String(b, CharSetName);
						content = "(" + Integer.toString(n) + "/"
								+ Integer.toString(m) + ")" + content;
					} else {
						content = new String(msg.getMsgContent(), CharSetName); // 正常短消息内容
					}
					break;

				case 4: // 二进制消息的处理
				default: // 未知的编码消息
					content_type = 4;
					content = Integer.toString(msg.getMsgFmt()) + ","+ msg.getMsgContent() + ","
							+ Integer.toString(msg.getTpPid()) + ","
							+ Integer.toString(msg.getTpUdhi()) + ","
							+ msg.getServiceId() + ","
							+ Integer.toString(msg.getRegisteredDeliver());
					break;
				}
			  ecode = 0;
			  //上行处理完毕，打印或进行其他业务逻辑
			  System.out.println(new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date())+"---------->上行消息:content="+content+",phone="+srcmobile+",append="+msg.getDestnationId());

			} else { // 1-状态报告

			srcmobile = msg.getSrcterminalId();
			String sendId = Util.byteArrayToHexString(msg.getStatusMsgId());
			String strStat = msg.getStat(); // 获得消息发送状态

			content_type = 2;
			content = sendId + "," + Util.DateToString(msg.getSubmitTime())
						+ "," + Util.DateToString(msg.getDoneTime()) + ","
						+ ecode;
			//状态报告处理完毕，打印或进行其他业务逻辑
			System.out.println(new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date())+"---------->状态报告:msgid="+sendId+",stat="+strStat+",phone="+srcmobile);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.onDeliver(msg); // 此处的返回必须要有！
	}
}
